/*
 * tmry.c
 *
 *  Created on: Apr 12, 2012
 *      Author: Rafal Sokolowski
 *      Comment: Obsluga przyciskow lacznie z funkcjami obslugujacymi przerwania.
 */

#include "tc.h"
#include "tmry.h"
#include "frame.h"

int timerRegister( int (*wskFun)( void ) ){ 		//Funkcja rejestrujaca funkcje, zwraca ID

	if (NULL == wskFun)
		return -1;

	int u32_ID = 0;
	g_au32Services[TIMER_PTR_COL][g_u16TimerServicesPointer] = (unsigned int) wskFun;
	g_au32Services[TIMER_ACT_COL][g_u16TimerServicesPointer] = 0; // nieaktywne as Default
	g_au32Services[TIMER_ID_COL][g_u16TimerServicesPointer] = g_u16TimerServicesPointer;

	u32_ID = g_au32Services[TIMER_ID_COL][g_u16TimerServicesPointer];
	g_u16TimerServicesPointer++;

	return u32_ID;
}

int timerStart( int _ID, int _timeout ){

	if ( (-1 >= _ID) || ( 0 >= _timeout) )
		return 1;
	g_au32Services[TIMER_TIMEOUT_COL][_ID] = _timeout;
	g_au32Services[TIMER_INC_COL][_ID] = 0;
	g_au32Services[TIMER_ACT_COL][_ID] = 1;
	return 0;
}

int timerStop( int _ID ){
	if ( -1 >= _ID )
		return 1;

	g_au32Services[TIMER_ACT_COL][_ID] = 0;
	return 0;
}

int timerProcessServices(void){
	int i = 0;
	int (*pFunctionTmp)( void );


	for (i = 0; i < g_u16TimerServicesPointer; i++){
		if(g_au32Services[TIMER_FN_PEDNING_COL][i]){
			pFunctionTmp = g_au32Services[TIMER_PTR_COL][i];			// wywolaj funkcje
			pFunctionTmp();
			g_au32Services[TIMER_FN_PEDNING_COL][i] = 0; // wywolalem
		}
	}
	g_oFlags.u8_ServicePending = 0; // wszystkie sprawdzilem nic nie czeka
	return 0;
}

__attribute__((__interrupt__)) void interruptTimer(void) {
	int i = 0;

	tc_read_sr(&AVR32_TC, 0);
	for (i = 0; i < g_u16TimerServicesPointer ; i++){
		if (1 == g_au32Services[TIMER_ACT_COL][i]) { // TODO zamien 1 na SERVICE_ACTIVE (makro)
			g_au32Services[TIMER_INC_COL][i]++;
			if (g_au32Services[TIMER_INC_COL][i] >= g_au32Services[TIMER_TIMEOUT_COL][i]){
				g_au32Services[TIMER_INC_COL][i] = 0;

				g_au32Services[TIMER_FN_PEDNING_COL][i] = 1;
				g_oFlags.u8_ServicePending = 1;
			}
		}
	}
//#error GRUPA2 DODAJ KANAL TUTAJ DLA TIMERA
//
	//TODO KANAL DLA TIMERA

}
